package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类

        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2.组装成父子的树形结构

        List<CategoryEntity> level1Menus = entities.stream().filter((item) -> item.getParentCid() == 0
        ).map(menu -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO:1.检查当前删除的菜单，是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);

    }

    /**
     * 找到catelogId的完整路径
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {

        ArrayList<Long> paths = new ArrayList<>();

        List<Long> parentPath = findParentPath(paths, catelogId);

        Collections.reverse(parentPath);


        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Transactional
//    @CacheEvict(value = {"category"},key = "'getLevel1Categorys'")
    @Override
    @Caching(evict = {
            @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
            @CacheEvict(value = "category",key = "'getCatelogJson'")

    })
    public void updateCascade(CategoryEntity category) {

        this.updateById(category);

        String name = category.getName();
        Long catelogId = category.getCatId();

        categoryBrandRelationService.updateCategory(catelogId, name);


        //TODO


    }

    @Cacheable(value = {"category"},key = "#root.methodName")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {

        long l = System.currentTimeMillis();

        List<CategoryEntity> categoryEntites = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        long l1 = System.currentTimeMillis();
        System.out.println("消耗时间：" + (l - l1));
        return categoryEntites;
    }

    @Override

    @Cacheable(value = {"category"},key = "#root.methodName")
    public Map<String, List<Catelog2Vo>> getCatelogJson() {

        //给缓存中放入JSON字符串，拿出的JSON字符串，还要逆转为能用的对象

        //加入缓存逻辑，缓存中存的是JSON字符串
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");


        if (StringUtils.isEmpty(catelogJson)) {

            //缓存中没有数据，查询数据库

            System.out.println("缓存没有命中......查询数据库...........");

                    

            Map<String, List<Catelog2Vo>> catelogJsonFromDB = getCatelogJsonFromDBWithRedisLock();

            System.out.println("数据库查询到的数据是："+catelogJsonFromDB);


            //查到的数据再放入缓存，查到的数据要转为json

            String s = JSON.toJSONString(catelogJsonFromDB);

            redisTemplate.opsForValue().set("catelogJson", s);

            return catelogJsonFromDB;


        }

        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catelogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        System.out.println("缓存命中....");
        return result;

    }

    /**
     * 从数据库查询品类数据
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDB() {

        /**
         * 优化：将多次数据库查询变为查询一次
         */
        
        synchronized (this){

            return getDataFromDB();

        }
    }

    private Map<String, List<Catelog2Vo>> getDataFromDB() {
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");

        if (!StringUtils.isEmpty(catelogJson)) {
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catelogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;

        }


        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //1.查出所有分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        Map<String, List<Catelog2Vo>> map = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(),
                //1.每个的一级分类，查到这个一级分类的二级分类
                v -> {
                    List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
                    List<Catelog2Vo> catelog2Vos = null;
                    if (categoryEntities != null) {

                        catelog2Vos = categoryEntities.stream().map(l2 -> {
                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                            //1.将当前二级分类的三级分类封装成vo
                            List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());


                            if (level3Catelog != null) {

                                List<Catelog2Vo.Catelog3Vo> catelog3Vos = level3Catelog.stream().map(l3 -> {

                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName().toString());

                                    return catelog3Vo;

                                }).collect(Collectors.toList());

                                catelog2Vo.setCatalog3List(catelog3Vos);

                            }

                            return catelog2Vo;

                        }).collect(Collectors.toList());
                    }
                    return catelog2Vos;
                }
        ));

        return map;
    }

    /**
     * 使用分布式锁
     * @param  
     * @param  
     * @return
     */

    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDBWithRedisLock() {

        /**
         * 优化：将多次数据库查询变为查询一次
         */

        String uuid = UUID.randomUUID().toString();
        //1.抢占分布式锁
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);

        //2.设置过期时间,必须和加锁同步的原子操作
//        redisTemplate.expire("lock",30, TimeUnit.SECONDS);


        if(lock){

            System.out.println("获取分布式锁成功....");
            Map<String, List<Catelog2Vo>> dataFromDB = null;
            try{
              dataFromDB = getDataFromDB();

            }finally {


//            redisTemplate.delete("lock");

                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";

                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }


            return dataFromDB;
        }else {
            //加锁失败...重试..自旋的方式
            //休眠100ms

            System.out.println("获取分布式锁失败...");

            return   getCatelogJsonFromDBWithRedisLock();
        }
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {

        List<CategoryEntity> collect = selectList.stream().filter(item -> {
            return item.getParentCid() == parent_cid;
        }).collect(Collectors.toList());

        return collect;
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
    }

    private List<Long> findParentPath(ArrayList<Long> paths, Long catelogId) {

        CategoryEntity byId = this.getById(catelogId);

        paths.add(byId.getCatId());

        if (byId.getParentCid() != 0) {
            findParentPath(paths, byId.getParentCid());

        }
        return paths;
    }

    //递归查询所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {


        List<CategoryEntity> childrens = all.stream().filter((entity) ->
                //1.找到子菜单
                entity.getParentCid().equals(root.getCatId())
        ).map(entity -> {
            entity.setChildren(getChildrens(entity, all));
            return entity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());


        return childrens;
    }

}